db = require '../utils/db'
path = require 'path'
fs = require 'fs'
config = require '../config'
createStatement = (model)->
	{tableName, table, unique} = model

	return  """
		CREATE TABLE `#{config.connection.production.database}`.`#{tableName}` (
		`id` INT NOT NULL AUTO_INCREMENT
		,#{( '`'+ k + '` ' + table[k].type + ' DEFAULT '+ (table[k].default || '\'\'') + ' COMMENT \'' + table[k].comment + '\''  for k of table).join(',')}
		,`create_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
		,`update_time` TIMESTAMP
		,PRIMARY KEY (`id`)
		#{if unique then ',' + ('UNIQUE INDEX `' + u + '` (`' + u + '` ASC)' for u in unique).join(' , ') else ''}
		)

	"""

_models = ( file.split('.')[0] for file in fs.readdirSync __dirname when file.split('.')[0] isnt 'index' )
_modules = ( {name:name,module:require './'+name} for name in _models)

for m in _modules
	module.exports[m.name] = m.module

if require.main is module
	# 创建表
	for k,model of module.exports 
		continue unless model.tableName
		db.runSql createStatement(model), ()->
			console.log arguments
	console.log 'run model init '